package cn.jilian.front.service.impl;


import com.baidu.aip.ocr.AipOcr;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableMap;

import cn.jilian.front.domain.IdCardBackInfo;
import cn.jilian.front.domain.IdNoInfo;
import cn.jilian.front.service.IdCardService;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

@Component("idCardHandler")
public class IdCardHandler implements IdCardService {
    @Autowired
    private AipOcr aipOcr;
    
    @Value("${enable.file.use.checksum}")
    private Boolean enableUseCheckSum;

    private ObjectMapper objectMapper = new ObjectMapper();

    private final Logger logger = LoggerFactory.getLogger(getClass());
    private static Map<String, String> idCardMap = ImmutableMap.<String, String>builder()
            .put("姓名", "name")
            .put("公民身份号码", "idNo")
            .put("住址", "addr")
            .put("民族", "nation")
            .put("出生", "birth")
            .put("性别", "gender")
            .build();

    private static Map<String, String> idCardBackMap = ImmutableMap.<String, String>builder()
            .put("签发日期", "activeTime")
            .put("失效日期", "expireTime")
            .put("签发机关", "signingOrg")
            .build();
    private IdNoInfo parseResponse(JSONObject json){
    	 if (json==null||!json.has("words_result")) {
         	logger.debug("response json has not words_result");
             return null;
         }
         Map<String, String> rs = new HashMap<>();
         try {
             JSONObject result = json.getJSONObject("words_result");
             for (String key : idCardMap.keySet()) {
            	 if(result.has(key)){
            		 JSONObject n = result.getJSONObject(key);
                     if (n != null) {
                         String v = n.getString("words");
                         rs.put(idCardMap.get(key), v);
                     }
            	 }
                 
             }
         } catch (Exception e) {
             e.printStackTrace();
         }
         IdNoInfo info = objectMapper.convertValue(rs, IdNoInfo.class);
         return info;
    }

//    @Override
//    public IdNoInfo handle(String path) {
//    	logger.debug("try to scan image[path={}] by baidu aipocr for ident info",path);
//        JSONObject json = aipOcr.idcard(path, true, new HashMap<String, String>());
//        return parseResponse(json);
//    }
//
//	@Override
//	public IdNoInfo handle(byte[] data) {
//		logger.debug("try to scan image from data bytes for ident info");
//		JSONObject json = aipOcr.idcard(data, true, new HashMap<String, String>());
//		 return parseResponse(json);
//	}

	@Override
	public IdNoInfo handleFrontSide(File file) {
		logger.debug("try to scan image[path={}] by baidu aipocr for ident info",file.getAbsolutePath());
		HashMap<String, String> options = new HashMap<String, String>();
	    options.put("detect_direction", "true");
	    options.put("detect_risk", "false");

		JSONObject json = aipOcr.idcard(file.getAbsolutePath(), "front", options);
		return parseResponse(json);
	}

	@Override
	public IdCardBackInfo handleBackSide(File file) {
		HashMap<String, String> options = new HashMap<String, String>();
	    options.put("detect_direction", "true");
	    options.put("detect_risk", "false");
		JSONObject json = aipOcr.idcard(file.getAbsolutePath(), "back", options);
		logger.debug("parser idCard back side response:{}",json);
		return parseBackResponse(json);
	}
	
	private IdCardBackInfo parseBackResponse(JSONObject json){
   	 if (json==null||!json.has("words_result")) {
        	logger.debug("response json has not words_result");
            return null;
        }
        Map<String, String> rs = new HashMap<>();
        try {
            JSONObject result = json.getJSONObject("words_result");
            for (String key : idCardBackMap.keySet()) {
           	 if(result.has(key)){
           		 JSONObject n = result.getJSONObject(key);
                    if (n != null) {
                        String v = n.getString("words");
                        rs.put(idCardBackMap.get(key), v);
                    }
           	 }
                
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        IdCardBackInfo info = objectMapper.convertValue(rs, IdCardBackInfo.class);
        return info;
   }
}
